//-----------------------------------------------------------------------------//
//                                                                             //
//         _____  _____  _    _   ______   _____    ______    _____            //
//        / ____||  __ \| |  | | |  ____| |  __ \  |  ____|  / ____|           //
//       | (___  | |__) | |__| | | |__    | |__) | | |__    | (___             //
//        \___ \ |  ___/|  __  | |  __|   |  _  /  |  __|    \___ \            //
//        ____) || |   _| |  | |_| |____ _| | \ \ _| |____ _ ____) |           //
//       |_____(_)_|  (_)_|  |_(_)______(_)_|  \_(_)______(_)_____(_)          //
//                                                                             //
//       Copyright  by  Mader Theodor,  Oeschger Roni,  Oskam Thomas           //
//       in  the  context of  the  ETH  Game  Programming  Lab, 2007           //
//                                                                             //
//-----------------------------------------------------------------------------//

#include "ObjParser.h"
#include <fstream>
#include <iostream>
#include <limits>
#include <cassert>

namespace Geometry
{


	bool ObjParser::Parse( vector<Vertex>& vertices, vector<Vertex>& normals, vector<Face>& faces ) {
		std::ifstream fIn( m_FileName.c_str() );
		if( !fIn.good() )
			return false;

		do{
			string element;
			fIn >> element;
			if( element == "v" ) {
				float x, y, z;
				fIn >> x >> y >> z;

				vertices.push_back( Vertex( x, y, z ) );
			}
			else if( element == "vn" ) {
				float x, y, z;
				fIn >> x >> y >> z;

				normals.push_back( Vertex( x, y, z ) );
			}
			else if( element == "f" ) {
				Face f;
				unsigned int t;

				// read data of first vertex
				fIn >> f.v1;
				char s; fIn >> s;			// skip / charakter

				// check if texture coordinate is present
				s = fIn.peek();			
				if( s != '/' ) {
					fIn >> t;
				}

				fIn >> s;
				fIn >> f.n1;


				// second vertex
				fIn >> f.v2;
				s; fIn >> s;
				s = fIn.peek();
				if( s != '/' ) {
					fIn >> t;
				}

				fIn >> s;
				fIn >> f.n2;

				// third vertex
				fIn >> f.v3;
				s; fIn >> s;
				s = fIn.peek();
				if( s != '/' ) {
					fIn >> t;
				}

				fIn >> s;
				fIn >> f.n3;

				faces.push_back( f );

			}

			else {
				char c;
				do {
					fIn.get( c );
				}
				while( c != '\n' && fIn.good() );
			}
		}
		while( fIn.good() );

		fIn.close();
		return true;
	}
}



